package com.k.kc.util;


import org.apache.commons.beanutils.ConvertUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class ReflectUtl {
    public static <T> T newInstance(Class<T> modelClass) throws IllegalAccessException, InstantiationException {
        return modelClass.newInstance();
    }

    public static <T> T setValueByField(Class<T> modelClass, Object[] value) throws IllegalAccessException, InstantiationException {
        T obj = newInstance(modelClass);
        Field[] fields = modelClass.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            if (Modifier.isStatic(field.getModifiers())) {
                continue;
            }
            String fieldName = field.getName();
            int fieldDefaultIndex = resolveFieldIndex(field, i);
            System.out.println("fieldName:" + fieldName + " fieldIndex:" + fieldDefaultIndex);
            Object valueConv = ConvertUtils.convert(value[fieldDefaultIndex], field.getType());
            field.setAccessible(true);
            field.set(obj, valueConv);
        }
        return obj;
    }


    public static <T> T setValueByMethod(Class<T> modelClass, Object[] value) throws InstantiationException, IllegalAccessException, InvocationTargetException {
        T obj = newInstance(modelClass);
        Method[] methods = modelClass.getDeclaredMethods();
        for (int i = 0; i < methods.length; i++) {
            Method method = methods[i];
            int methodDefaultIndex = resolveMethodIndex(method, i);
            String methodName = method.getName();
            System.out.println("methodName:" + methodName + " methodIndex:" + methodDefaultIndex);
            if (methodName.startsWith("set")) {
                //System.out.println(methodName);
                //method.invoke(obj, value[methodIndex]);
            }
        }
        return obj;
    }

    /**
     * field 排序
     *
     * @param field        field
     * @param defaultIndex defaultIndex
     * @return index
     */
    private static int resolveFieldIndex(Field field, int defaultIndex) {
        return defaultIndex;
    }

    /**
     * method 排序
     *
     * @param method       method
     * @param defaultIndex defaultIndex
     * @return index
     */
    private static int resolveMethodIndex(Method method, int defaultIndex) {
        return defaultIndex;
    }
}
